package com.nondo.dean.platform.service;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.platform.domain.Freight;
import com.nondo.dean.platform.domain.Grade;
import com.nondo.dean.platform.domain.ProductDiscount;
import com.nondo.dean.platform.domain.ProductDiscountExample;
import com.nondo.dean.platform.domain.Zone;
import com.nondo.dean.platform.mapper.ProductDiscountMapper;
import com.nondo.dean.platform.model.UserBean;
import com.nondo.dean.platform.model.param.ProductPriceParam;
import com.nondo.dean.platform.model.result.PriceResult;
import com.nondo.dean.platform.model.result.ProductDiscountResult;
import com.nondo.dean.platform.model.result.ProductResult;

/**
 * 产品折扣率管理业务类
 * 
 * @author zhaoljin
 * @date 2018年4月3日
 */
@Component
public class ProductDiscountService {
    
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private ProductService productService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ProductDiscountMapper productDiscountMapper;
    
    @Autowired
    private ZoneService zoneService;
    
    @Autowired
    private GradeService gradeService;
    
    @Autowired
    private FreightService freightService;

    /**
     * 插入产品折扣率
     * @param productDiscount
     * @return
     */
    @Transactional
    public int addProductDiscount(ProductDiscount productDiscount) {
        return productDiscountMapper.insertSelective(productDiscount);
    }

    /**
     * 修改产品折扣率
     * @param productDiscount
     * @return
     */
    @Transactional
    public int updateProductDiscount(ProductDiscount productDiscount) {
        return productDiscountMapper.updateByPrimaryKeySelective(productDiscount);
    }

    /**
     * 按照主键ID查询产品折扣率
     * @param id
     * @return
     */
    public ProductDiscount selectProductDiscount(Integer id) {
        return productDiscountMapper.selectByPrimaryKey(id);
    }

    /**
     * 产品折扣率分页查询列表
     * @param offset
     * @param limit
     * @param productDiscount
     * @return
     */
    public List<ProductDiscount> getProductDiscountList(int offset, int limit, ProductDiscount productDiscount) {
        ProductDiscountExample example = new ProductDiscountExample();
        example.setOrderByClause("create_date DESC");
        RowBounds rowBounds = new RowBounds(offset, limit);
        ProductDiscountExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, productDiscount);
        return productDiscountMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    /**
     * 产品折扣率总数统计
     * @param productDiscount
     * @return
     */
    public Long count(ProductDiscount productDiscount) {
        ProductDiscountExample example = new ProductDiscountExample();
        ProductDiscountExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, productDiscount);
        return productDiscountMapper.countByExample(example);
    }

    /**
     * 组装查询条件
     * @param criteria
     * @param productDiscount
     */
    void setCriteria(ProductDiscountExample.Criteria criteria, ProductDiscount productDiscount) {
        if (productDiscount != null) {
            if (productDiscount.getId() != null)
                criteria.andIdEqualTo(productDiscount.getId());
            if (productDiscount.getUserId() != null)
                criteria.andUserIdEqualTo(productDiscount.getUserId());
            if (productDiscount.getProductId() != null)
                criteria.andProductIdEqualTo(productDiscount.getProductId());
        }
        criteria.andDelFlagEqualTo(String.valueOf(0));
    }

    /**
     * 将DO对象转成VO对象
     * @param productDiscountDb {@link ProductDiscount}
     * @return 产品折扣率 {@link productDiscountResult}
     */
    public ProductDiscountResult getProductDiscountResult(ProductDiscount productDiscountDb) {
        ProductDiscountResult productDiscountResult = new ProductDiscountResult();
        if (productDiscountDb == null) {
            return productDiscountResult;
        }
        BeanUtils.copy(productDiscountDb, productDiscountResult);
        Integer userId = productDiscountDb.getUserId();
        UserBean user = userService.getUserById(userId);
        String userName = user.getUserName();
        productDiscountResult.setUserName(userName);
        Integer productId = productDiscountDb.getProductId();
        ProductResult product = productService.getProductBeanById(productId);
        String productName = product.getName();
        productDiscountResult.setProductName(productName);
        return productDiscountResult;
    }

    /**
     * 根据经销商和产品ID获取产品折扣率
     * @param userId 经销商ID
     * @param productId 产品ID
     * @return {@link ProductDiscount}
     */
    public ProductDiscount getProductDiscountByUserAndProductId(Integer userId, Integer productId) {
        ProductDiscountExample example = new ProductDiscountExample();
        ProductDiscountExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdEqualTo(productId);
        criteria.andDelFlagEqualTo(String.valueOf(0));
        List<ProductDiscount> productDiscountList = productDiscountMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(productDiscountList)?productDiscountList.get(0):null;
    }

    /**
     * 计算产品价格
     * @param request
     * @param response
     * @param param 封装了区域和经销商等级的VO对象 {@link ProductPriceParam}
     * @return
     */
    public PriceResult getProductDiscount(ProductPriceParam param) {
        PriceResult priceResult = new PriceResult();
        BigDecimal salePrice = param.getSalePrice();
        ProductDiscount productDiscount = getProductDiscountByUserAndProductId(param.getUserId(), param.getProductId());
        if (productDiscount != null) {
            // 1.根据经销商和产品ID获取产品折扣率,如果经销商对该产品单独设置了产品折扣,使用此折扣计算产品价格
            BigDecimal baseValue = new BigDecimal(100);
            priceResult.setDiscount(productDiscount.getDiscount().divide(baseValue));
            priceResult.setFinalPrice(salePrice.multiply(priceResult.getDiscount()));
        } else {
            // 2.根据区域，经销商等级，运费在不同区域的折扣率计算产品价格，最终价格=产品价格*(1-区域折扣率-等级折扣率+运费折扣率)
            priceResult = getProductPriceByZoneAndGrade(param);
        }
        return priceResult;
    }

    /**
     * 区域经销商产品价格计算
     * @param param {@link ProductPriceParam}
     * @return
     */
    private PriceResult getProductPriceByZoneAndGrade(ProductPriceParam param) {
        PriceResult priceResult = new PriceResult();
        BigDecimal salePrice = param.getSalePrice();
        BigDecimal baseValue = new BigDecimal(100);
        // 1.根据区域获得折扣率
        Zone zone = zoneService.selectZone(param.getZoneId());
        BigDecimal zdiscount = zone.getDiscount().divide(baseValue);
        priceResult.setZdiscount(zdiscount);
        // 2.根据等级获得折扣率
        Grade grade = gradeService.selectGrade(param.getGradeId());
        BigDecimal gdiscount = grade.getDiscount().divide(baseValue);;
        priceResult.setGdiscount(gdiscount);
        // 3.根据区域获得运费折扣率
        Freight freight = freightService.getFreightByZoneId(param.getZoneId());
        BigDecimal fdiscount = freight.getDiscount().divide(baseValue);;
        priceResult.setFdiscount(fdiscount);
        // 4.最终价格=产品价格*(1-区域折扣率-等级折扣率+运费折扣率)
        float discount = 1-(zdiscount.floatValue()+gdiscount.floatValue())+fdiscount.floatValue();
        priceResult.setDiscount(new BigDecimal(discount));
        float price = salePrice.floatValue()*discount;
        priceResult.setFinalPrice(new BigDecimal(price));
        return priceResult;
    }

}
